import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RouteLocationNormalized } from 'vue-router'

export interface TabItem {
  path: string
  name: string
  title: string
  closable: boolean
}

export const useAppStore = defineStore('app', () => {
  const locale = ref<'zh' | 'en'>('zh')
  const collapsed = ref(false)
  const tabs = ref<TabItem[]>([])
  const activeTab = ref<string>('')

  const setLocale = (lang: 'zh' | 'en') => {
    locale.value = lang
    if (typeof window !== 'undefined') {
      localStorage.setItem('locale', lang)
    }
  }

  const toggleSidebar = () => {
    collapsed.value = !collapsed.value
  }

  // Tab管理功能
  const addTab = (route: RouteLocationNormalized) => {
    const { path, name, meta } = route
    
    // 如果路由标记为不在Tab中显示，则直接返回
    if (meta.hideInTab) {
      return
    }
    
    // Dashboard标签页不可关闭
    const closable = path !== '/dashboard'
    
    // 检查标签页是否已存在
    const existingTab = tabs.value.find(tab => tab.path === path)
    if (!existingTab) {
      const newTab: TabItem = {
        path,
        name: name as string,
        title: meta.title as string,
        closable
      }
      tabs.value.push(newTab)
    }
    
    // 设置当前激活的标签页
    activeTab.value = path
  }

  const removeTab = (path: string) => {
    const index = tabs.value.findIndex(tab => tab.path === path)
    if (index > -1) {
      tabs.value.splice(index, 1)
      
      // 如果删除的是当前激活的标签页，需要切换到其他标签页
      if (activeTab.value === path) {
        if (tabs.value.length > 0) {
          // 优先选择右侧的标签页，如果没有则选择左侧的
          const newActiveTab = tabs.value[index] || tabs.value[index - 1]
          activeTab.value = newActiveTab.path
        } else {
          activeTab.value = ''
        }
      }
    }
  }

  const removeOtherTabs = (currentPath: string) => {
    tabs.value = tabs.value.filter(tab => tab.path === currentPath || !tab.closable)
    activeTab.value = currentPath
  }

  const removeAllTabs = () => {
    tabs.value = tabs.value.filter(tab => !tab.closable)
    if (tabs.value.length > 0) {
      activeTab.value = tabs.value[0].path
    } else {
      activeTab.value = ''
    }
  }

  const setActiveTab = (path: string) => {
    activeTab.value = path
  }

  // 初始化默认标签页（Dashboard）
  const initTabs = () => {
    if (tabs.value.length === 0) {
      tabs.value.push({
        path: '/dashboard',
        name: 'Dashboard',
        title: 'dashboard',
        closable: false
      })
      activeTab.value = '/dashboard'
    }
  }

  // 初始化语言设置
  const initLocale = () => {
    if (typeof window !== 'undefined') {
      const savedLocale = localStorage.getItem('locale') as 'zh' | 'en'
      if (savedLocale) {
        locale.value = savedLocale
      }
    }
  }
  
  initLocale()
  initTabs()

  return {
    locale,
    collapsed,
    tabs,
    activeTab,
    setLocale,
    toggleSidebar,
    addTab,
    removeTab,
    removeOtherTabs,
    removeAllTabs,
    setActiveTab,
  }
})
